//
//  STFollowListViewController.swift
//  Story
//
//  Created by 汤泽川 on 2019/5/10.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import PKHUD

class STFollowListViewController: UIViewController {

    let userDatas = BehaviorRelay<[STUserInfo]>(value: [])
    var currentPage = 0
    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        let userTableView = UITableView()
        self.view.addSubview(userTableView)
        userTableView.register(STFollowLisTableViewCell.self, forCellReuseIdentifier: "STFollowLisTableViewCell")
        userTableView.separatorStyle = .none
        userTableView.backgroundColor = UIColor.init(white: 0, alpha: 0.03)
        userTableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        userTableView.gtm_addRefreshHeaderView {
            STUserService.shareInstance.fetchFollowList(page: 0, count: 20).result(callBackWithData: { (infos, error) in
                if infos != nil {
                    self.currentPage = 0
                    self.userDatas.accept(infos!)
                }
                if error != nil {
                    HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
                }
                userTableView.endRefreshing(isSuccess: error == nil)
            })
        }
        userTableView.gtm_addLoadMoreFooterView {
            STUserService.shareInstance.fetchFollowList(page: self.currentPage + 1, count: 20).result(callBackWithData: { (infos, error) in
                if infos != nil {
                    self.userDatas.accept(self.userDatas.value + infos!)
                }
                if error != nil {
                    HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
                }
                userTableView.endLoadMore(isNoMoreData: infos?.count == 0)
            })
        }
        self.userDatas.bind(to: userTableView.rx.items) { (tableView, row, element) in
            let cell = tableView.dequeueReusableCell(withIdentifier: "STFollowLisTableViewCell") as! STFollowLisTableViewCell
            cell.selectionStyle = .none
            cell.configureCell(userInfo: element)
            return cell
            }
            .disposed(by: disposeBag)
        userTableView.rx.modelSelected(STUserInfo.self).subscribe(onNext: { (info) in
            let storyManager = STSearchAuthorListServiceManager(pageCount: 20)
            storyManager.authorName = info.username
            let collectVC = STUserStoryFeedViewController(storyManager: storyManager)
            collectVC.title = "\(info.username)写的的故事"
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(collectVC, animated: true)
        }).disposed(by: disposeBag)
        userTableView.triggerRefreshing()
    }
    
}
